/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package snail.data;

import java.util.Date;
import java.util.List;
import org.hibernate.Query;
import snail.model.Article;

/**
 *
 * @author hellmer
 */
public class ArticleDAO extends GenericHibernateDAO<Article, Integer>
        implements IArticleDAO {

    public List<Article> getByCategoryId(int id) {
        if (id == 0) {
            return this.getAll();
        }

        Query q = getSession().getNamedQuery(IArticleDAO.QUERY_BYCATEGORYID);
        q.setParameter("id", id);
        q.setParameter("date", new Date());
        return (List<Article>) q.list();
    }

    @Override
    public List<Article> getAll() {

        Query q = getSession().getNamedQuery(IArticleDAO.QUERY_ALL);
        q.setParameter("date", new Date());
        return (List<Article>) q.list();

    }

    public List<Article> search(String q) {
        return search(q, 0);
    }

    public List<Article> search(String q, int categoryId) {
        String query = "from Article where ";
        String[] keywords = q.split(" ");
        int i = 0;
        for (String k : keywords) {
            query += "Concat(title,description) like :p" + i++ + " AND ";
        }

        query = query.substring(0, query.length() - 5);
        if (categoryId != 0) {
            query += " AND categoryid = " + categoryId;
        }
        query += " AND expireDate > :date order by articleId desc";
        Query qq = getSession().createQuery(query);
        i = 0;
        for (String k : keywords) {
            qq.setParameter("p" + i++, "%" + k + "%");
        }
        qq.setParameter("date", new Date());
        System.out.print(query);
        return qq.list();

    }

    public List<Article> getAllExpired() {
        Query q = getSession().getNamedQuery(IArticleDAO.QUERY_ALLEXPIRED);
        q.setParameter("date", new Date());
        return (List<Article>) q.list();
    }
}
